#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#define THD_NUM 5

typedef struct thread_info{
  int _number;
  pthread_t _tid;
}thread_info;

void* thread_run(void* args)
{
  int num = *(int*)args;
  printf("我是新线程[%d], my tid = %lu \n", num, pthread_self());
  sleep(6);
  
  thread_info* info = (thread_info*)malloc(sizeof(thread_info));
  info->_number = num;
  info->_tid = pthread_self();
  //可以使用return终止，也可以使用pthread_exit终止
  //return info;
  pthread_exit(info);
  //if (num == 3){
  //  printf("我是三号线程\n");
  //  int a = 10;
  //  printf("%d\n", a / 0);
  //}
  //while (1){
  //  sleep(1);
  //} 
}

int main()
{
  //pthread_t tid;
  pthread_t tid_arr[THD_NUM];

  //创建线程
  for (size_t i = 0; i < THD_NUM; i++){
    pthread_create(tid_arr + i, NULL, thread_run, (void*)&i);
    sleep(1);
  }

  //打印线程信息
  printf("#################begin#########################\n");
  for (size_t i = 0; i < THD_NUM; i++){
    printf("我创建的  %lu 子进程 tid = %lu\n", i, tid_arr[i]);
  }
  printf("################# end ########################\n");

  //回收线程退出信息
  thread_info* info_arr[THD_NUM];
  for (size_t i = 0; i < THD_NUM; i++){
    pthread_join(tid_arr[i], (void**)(info_arr + i));
  }

  //打印子线程信息
  for (size_t i = 0; i < THD_NUM; i++){
    printf("%lu 号子线程 number = %d, tid = %lu\n", i, (info_arr[i])->_number, (info_arr[i])->_tid);
  }

  sleep(100);
  return 0;
}
